﻿using Shake.Domain.Infrastructures;
using Shake.Framework.Infrastructure;
using Shake.Framework.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shake.Framework.Setup
{
    /// <summary>
    /// 生成实体的前端的Model
    /// </summary>
    public class BuildFrontEntityModelSetup
    {
        public static void Initialize()
        {
            Task.Run(() =>
            {
#if DEBUG
                var features = FeatureUtil.GetFeatureAssembly();

                var entities = ReflectUtil.GetClassByBaseType<ShakeEntity>();

                var modelPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "public/models");

                if (!Directory.Exists(modelPath)) Directory.CreateDirectory(modelPath);

                foreach (var entity in entities)
                {
                    var instance = entity.Assembly.CreateInstance(entity.FullName);
                    var defaultJson = Newtonsoft.Json.JsonConvert.SerializeObject(instance);
                    var format = "define(function(){ return function(){return " + defaultJson + " }})";
                    var target = Path.Combine(modelPath, entity.Name + ".js");

                    File.WriteAllText(target, format);
                }

#endif
            });

        }
    }
}
